<template>
	<view class="order">
		<view class="order_nav">
			<!-- isActive -->
			<view class="order_nav_item" :class="{'isActive':tabCurrentIndex==index}" v-for="(item,index) in navList"
				:key="item.state" @tap="tabClick(item,index)">{{item.text}}</view>
		</view>
		<!-- 显示订单数据 -->
		<view class="order_conter">

			<swiper class="swiper" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item class="tab-content" v-for="(tag, key) in navList" :key="tag.state">

					<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">

						<!-- 空白页 -->
						<view class="order_conter_items" v-if="tag.loaded === true && orderList.length === 0">
							<!-- 没有找到任何订单 -->
							<wanl-empty text="没有找到任何订单" />
						</view>
						<view class="makeAppointment_item" v-for="(order, okey) in orderList" :key="order.id">
							<view class="makeAppointment_item_title">{{ order.stateTip }}</view>
							<view class="makeAppointment_item_conter" v-for="(goods, gkey) in order.goods"
								:key="goods.id" @tap="orderDetails(order.id)">
								<view class="makeAppointment_item_demo">

									<view class="makeAppointment_item_demo_left">
										<view class="image">
											<image :src="$wanlshop.oss(goods.image, 70, 70)" mode="aspectFill"></image>
										</view>
										<view class="conter">{{goods.title}}</view>
									</view>
									<view class="number">
										<view>×{{ goods.number }}</view>
										<!-- 退款状态:0=未退款,1=退款中,2=待退货,3=退款完成 -->
										<view class="number1" v-if="goods.refund_status != 0">
											{{getRefund(goods.refund_status)}}</view>
									</view>

								</view>
								<view class="price">实付款￥{{ order.pay.price }}</view>
							</view>
							<view class="makeAppointment_item_make" v-if="order.state == 1">
								<view class="name3 name4" @tap="cancelOrder(order)">取消订单
								</view>
								<view class="name1" @click="getPay(order)">去支付</view>
							</view>
							<view class="makeAppointment_item_make" v-if="order.state == 2">
								<view class="name2" :class="{isactive:order.isreminders==1}" @click="getReminders(order)"> {{order.isreminders==1?'已催单':'催单'}} </view>
							</view>

							<view class="makeAppointment_item_make" v-if="order.state == 3">
								<view class="name3 name4" @tap="onLogistics(order)">查看物流</view>
								<view class="name3" @tap="confirmOrder(order)">确认收货</view>
							</view>
							<view class="makeAppointment_item_make" v-if="order.state == 4">
								
								<time-selector v-if="order.appt_status==0"  showType="dateToTime" :beginDate="beginDate" endDate="2030-12-31"
									:beginTime="beginTime" endTime="23:59:59" @btnConfirm="btnConfirm"
									@btnCancel="btnCancel">
									<view class="name3 name4"  @click="open(order)">预约安装
									</view>
								</time-selector>
								<view class="name3 name4" v-if="order.appt_status==1" @click="getMakeAppointment">已预约 
								</view>
								<view class="name3 name4" v-if="order.appt_status==2" @click="getMakeAppointment">安装完成
								</view>
								
								<view class="name3 name4" @tap="onLogistics(order)">查看物流</view>
								
								<view class="name3 name4" @tap="commentOrder(order.id)">去评价</view>
							</view>
							<view class="makeAppointment_item_make" v-if="order.state ==6">
								<view class="name3 " @tap="deleteOrder(order.id,okey)">删除订单</view>
							</view>
							<view class="makeAppointment_item_make" v-if="order.state ==7">
								<view class="name3 " @tap="deleteOrder(order.id,okey)">删除订单</view>
							</view>
						</view>
					</scroll-view>

				</swiper-item>
			</swiper>
		</view>
	</view>
</template>
<script>
	import wanlEmpty from '@/components/wanl-empty/wanl-empty.vue'
	import timeSelector from "@/components/wing-time-selector/wing-time-selector.vue"
	export default {
		data() {
			return {
				// 导航选中对应的值改变字体颜色
				tabCurrentIndex: 0,
				// 开始日期
				beginDate: '',
				// 开始时间
				beginTime: '',
				time: new Date(),
				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',
						current_page: 1,
						// orderList: []
					},
					{
						state: 1,
						text: '待付款',
						loadingType: 'more',
						current_page: 1,
						// orderList: []

					},
					{
						state: 2,
						text: '待发货',
						loadingType: 'more',
						current_page: 1,
						// orderList: []

					},
					{
						state: 3,
						text: '待收货',
						loadingType: 'more',
						current_page: 1,
						// orderList: []

					},
					{
						state: 4,
						text: '待评价',
						loadingType: 'more',
						current_page: 1,
						// orderList: []

					}
				],
				orderList:[],
				// 订单id
				id: '',
				// 预约安装时间
				appttime: '',
				price: '0.00',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: [], //支付列表
				order_id:''
			}
		},
		computed: {

		},
		components: {
			wanlEmpty,
			timeSelector
		},
		methods: {
			handleMessage(evt) {
				this.log('接收到的消息：' + JSON.stringify(evt.detail));
			},

			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.loadData();
				// 'tabChange'
				// console.log('e', e)
			},
			// 选择预约时间
			btnConfirm(e) {
				// console.log('确定时间为：', e);
				// this.time = e.value;
				this.appttime = e.key;
				this.$api.get({
					url: '/wanlshop/product/Appointment',
					data: {
						id: this.id,
						appttime: this.appttime
					},
					success: res => {
						console.log('res', res)
						this.loadData();
						uni.navigateTo({
							url: '../makeAppointment/makeAppointment'
						})

					}
				});
			},
			//取消订单- 设置为7 -全局
			cancelOrder(item) {
				uni.showLoading({
					title: '请稍后'
				});
				// 获取列表
				this.$api.post({
					url: '/wanlshop/order/cancelOrder',
					data: {
						id: item.id
					},
					success: res => {
						let {
							stateTip,
							stateTipColor
						} = this.orderStateExp(7);
						item = Object.assign(item, {
							state: 7,
							stateTip,
							stateTipColor
						});
						this.$store.commit('statistics/order', {
							pay: this.$store.state.statistics.order.pay - 1
						});
						// 取消订单后删除待付款中该项，并修改全部中的状态 1.0.2升级
						// let list = this.navList[1].orderList;
						// let index = list.findIndex(val => val.id === item.id);
						// index !== -1 && list.splice(index, 1);
						// 删除后修改全部中的为7
						// if (this.tabCurrentIndex == 1) {
						// 	let list = this.navList[0].orderList;
						// 	let index = list.findIndex(val => val.id === item.id);
						// 	if (index !== -1) {
						// 		list[index].state = 7;
						// 	}
						// }
						uni.hideLoading();
					}
				});
			},
			// 催单
			getReminders(order) {
				var id = order.id
				if (order.isreminders == 0) {
					this.$api.get({
						url: '/wanlshop/order/Reminders',
						data: {
							id: id,
						},
						success: res => {
							if(res.code==0){
								this.$wanlshop.msg('催单失败');
							}else if(res.code==1){
								this.$wanlshop.msg(res.msg);
								this.loadData();
							}
							console.log('res', res)
							
						}
					});
				} else if (order.isreminders == 1) {
					this.$wanlshop.msg('您已提醒过商家了，请不要再催了');
				}

			},
			// 点击支付按钮支付金额
			getPay(item) {
				console.log('item', item)
				this.$api.post({
					url: '/wanlshop/pay/getPay',
					data: {
						order_id: item.id
					},
					success: res => {
						console.log('订单号', res)
						// uni.hideLoading();
						this.price = res.price;
						this.order_no = '订单号：' + res.order_no;
						this.order_pay_no = res.pay_no;
						this.order_id = res.order_id;
					}
				});
				var that=this;
				uni.showModal({
					title: '提示',
					content: '是否确认支付订单？',
					success: function(res) {
						if (res.confirm) {
							let data = null;
							that.payList.map((value, index, array) => {
								if (value.select) {
									data = value;
									console.log('value:',value);
								} else {
									return;
								}
							});
							// 获取小程序code
							// #ifdef MP
							uni.login({
							    success: (e) => {
									that.wanlPay(data, e.code);
							    },
							    fail: (e) => {
							        uni.showModal({
							            content: "无法获取微信code,原因为: " + e.errMsg,
							            showCancel: false
							        })
							    }
							})
							// #endif
							// #ifndef MP
							that.wanlPay(data);
							// #endif
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 删除订单	
			deleteOrder(order_id, key) {
				console.log('订单', order_id);
				uni.showLoading({
					title: '请稍后'
				});
				this.$api.post({
					url: '/wanlshop/order/delOrder',
					data: {
						id: order_id
					},
					success: res => {
						console.log('res',res);
						// this.navList[this.tabCurrentIndex].orderList.splice(key, 1);
						this.loadData();
						uni.hideLoading();
					}
				})
			},
			// 预约时间取消
			btnCancel() {
				console.log('取消时间：');
			},
			//确认收货- 全局
			confirmOrder(item) {
				uni.showLoading({
					title: '请稍后'
				});
				console.log('order_id', item.id)
				// 获取列表
				this.$api.post({
					url: '/wanlshop/order/confirmOrder',
					data: {
						id: item.id
					},
					success: res => {
						console.log('确认收获', res)
						let {
							stateTip,
							stateTipColor
						} = this.orderStateExp(4);
						item = Object.assign(item, {
							state: 4,
							stateTip,
							stateTipColor
						});
						this.tabCurrentIndex = 4;
						this.$store.commit('statistics/order', {
							receiving: this.$store.state.statistics.order.receiving - 1,
							evaluate: this.$store.state.statistics.order.evaluate + 1
						});
						this.loadData();
						uni.hideLoading();
					}
				});
			},
			//顶部tab点击
			tabClick(item, index) {
				this.tabCurrentIndex = index;
				console.log('item', item)
				// this.loadData();
			},
			commentOrder(id) {
				this.$wanlshop.to('../MyComments/MyComments?order_id=' + id);
			},
			confirm(e) {
				this.appttime = e.fulldate;
				console.log('e', this.appttime)

				// console.log('e', e);
			},
			open(order) {
				// this.$refs.calendar.open();
				this.id = order.id
				console.log('id', this.id)

			},
			// 点击已预约跳转到预约安装页面
			getMakeAppointment() {
				uni.navigateTo({
					url: '../makeAppointment/makeAppointment'
				})
			},
			getRefund(status) {
				return ["退款", "退款中", "待退货", "退款完成", "退款关闭", "退款被拒"][status];
			},
			// 点击查看物流跳转到查看物流页面
			onLogistics(item) {
				console.log('eeeee', item);

				uni.navigateToMiniProgram({
					appId: 'wx6885acbedba59c14',
					path: 'pages/result/result?nu=' + item.express_no + '&com=' + item.express_name +
						'&querysource=third_xcx',
					envVersion: 'release',
					success(res) {
						// 打开成功
						console.log('查看物流', res);
					},
					fail(res) {
						console.log('失败')
					}
				})

			},
			// 点击跳转到订单详情
			orderDetails(order_id) {

				this.$wanlshop.to('../../mines/order/Order_details?id=' + order_id);
				console.log('id', order_id)
			},
			//获取订单列表
			loadData(source) {
				console.log('dsgdhdfjf')
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let state = navItem.state;

				//判断是否最后一页
				// if (navItem.loadingType == 'noMore') {
				// 	return;
				// }
				//tab切换只有第一次需要加载数据
				// if (source === 'tabChange' && navItem.loaded === true) {
				// 	return;
				// }
				//防止重复加载
				// if (navItem.loadingType === 'loading') {
				// 	return;
				// }
				// navItem.loadingType = 'loading';
				// 获取列表
				this.$api.get({
					url: '/wanlshop/order/getOrderList',
					data: {
						state: state,
						page: navItem.current_page
					},
					success: res => {
						console.log('reser', res)
						navItem.current_page = res.current_page; //当前页码
						// if (res.last_page === res.current_page) {
						// 	navItem.loadingType = 'noMore';
						// } else {
						// 	navItem.loadingType = 'more';
						// 	navItem.current_page++;
						// }
						let orderList = res.data.filter(item => {
							//添加不同状态下订单的表现形式
							item = Object.assign(item, this.orderStateExp(item.state));
							//演示数据所以自己进行状态筛选
							if (state === 0) {
								//0为全部订单
								return item;
							}
							return item.state === state;
						});
						this.orderList=res.data
						// orderList.forEach(item => {
						// 	navItem.orderList.push(item);
						// });
						console.log('res12', navItem)
						//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
						this.$set(navItem, 'loaded', true);
					}
				});
			},
			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#ff3200';
				switch (+state) {
					case 1:
						stateTip = '等待支付';
						break;
					case 2:
						stateTip = '等待卖家发货';
						break;
					case 3:
						stateTip = '卖家已发货';
						break;
					case 4:
						stateTip = '交易成功';
						break;
					case 5:
						stateTip = '交易成功';
						break;
					case 6:
						stateTip = '已完成';
						break;
					case 7:
						stateTip = '订单已关闭';
						stateTipColor = '#909399';
						break;
						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			},
			async wanlPay(data, code = null) {
				this.$api.post({
					url: '/wanlshop/pay/payment',
					data: {
						type: data.type,
						method: data.method,
						code: code,
						order_id: this.order_id
					},
					success: (res) => {
						console.log('选择支付方式', res);

						// 微信 H5支付
						if (data.type == 'wechat' && data.method == 'wap') {
							// 关闭loading
							this.loading = false;
							uni.showModal({
								title: '微信支付',
								content: '是否已完成支付',
								success: (res) => {
									if (res.confirm) {
										this.paySuccess();
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
							// 异步查询是否支付成功
							window.location.href = res;
						}

						// 微信小程序支付
						if (data.type == 'wechat' && data.method == 'miniapp') {
							uni.requestPayment({
								appId: res.appId,
								nonceStr: res.nonceStr, //支付密钥
								package: res.package,
								paySign: res.paySign,
								signType: res.signType, //加密方式
								timeStamp: res.timeStamp, //时间戳
								success: (res) => {
									console.log('成功支付', res)
									this.paySuccess();
								},
								fail: (e) => {
									console.log('e',e)
									uni.showModal({
										content: "支付失败,原因为: " + e.errMsg,
										showCancel: false
									})
								}
							})
						}

					}
				});
			},
			// 支付成功
			paySuccess() {

				this.loading = false;
				this.$store.commit('statistics/order', {
					pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
					delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
				});
				console.log('支付成功1')
				this.$wanlshop.to('/pages/page/success?type=pay');
			},
			getPayment() {
				let method = 'wap';
				// #ifdef APP-PLUS
				method = 'app';
				// #endif
				// #ifdef MP-BAIDU
				method = 'mini';
				// #endif
				// #ifdef MP-WEIXIN
				method = 'miniapp';
				// #endif
				// #ifdef MP-ALIPAY
				method = 'mini';
				// #endif
				// #ifdef MP-QQ
				method = 'mini';
				// #endif
				this.payList = [{
					name: '余额支付',
					describe: '',
					type: 'balance',
					method: 'balance',
					state: this.isbalance ? true : false, // 是否可用
					select: this.isbalance ? true : false // 是否选中
				}];
				// #ifdef H5
				this.payList.push({
					name: '支付宝',
					describe: '',
					type: 'alipay',
					method: method,
					state: true,
					select: false
				}, {
					name: '微信支付',
					describe: '推荐使用微信支付',
					type: 'wechat',
					method: method,
					state: true,
					select: this.isbalance ? false : true
				});
				// #endif
				// #ifndef H5
				uni.getProvider({
					service: "payment",
					success: (e) => {
						e.provider.map((value) => {
							if (value == 'alipay') {
								this.payList.push({
									name: '支付宝',
									describe: '',
									type: value,
									method: method,
									state: true,
									select: false
								});
							} else if (value == 'wxpay') {
								this.payList.push({
									name: '微信支付',
									describe: '推荐使用微信支付',
									type: 'wechat',
									method: method,
									state: true,
									select: this.isbalance ? false : true
								});
							} else if (value == 'baidu') {
								this.payList.push({
									name: '百度收银台',
									describe: '',
									type: value,
									method: method,
									state: true,
									select: false
								});
							} else if (value == 'appleiap') {
								this.payList.push({
									name: 'Apple支付',
									describe: '',
									type: 'apple',
									method: method,
									state: true,
									select: false
								});
							}
						})
					}
				});
				// #endif
			},
		},
		onLoad(options) {
			if (!options.state) {
				options.state = 0;
			}
			this.tabCurrentIndex = +options.state;
			// #ifndef MP
			this.loadData();
			// #endif
			// #ifdef MP
			if (options.state == 0) {
				this.loadData();
			}
			// #endif
			// 获取系统当前时间
			var data = this.$wanlshop.timeFormat();
			this.beginDate = data.split(' ')[0];
			this.beginTime = data.split(' ')[1];
			// console.log('a', data.split(' '))
			this.$api.post({
				url: '/wanlshop/pay/getBalance',
				success: res => {
					console.log('res11', res)
					this.$store.commit('user/setUserInfo', {
						money: res
					});
					// 获取支付列表
					this.getPayment();
				}
			});
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f0f0f0;
	}

	.order {
		&_nav {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			background-color: #FFFFFF;
			display: flex;
			justify-content: space-around;
			align-items: center;
			width: 750rpx;
			height: 80rpx;
			z-index: 99999;

			&_item {
				font-size: 26rpx;
				color: #4b4b4b;
				background-color: #FFFFFF;
				width: 150rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				box-sizing: border-box;
			}

			.isActive {
				color: #ff3200;
				border-bottom: 2px solid #ff3200;
			}
		}

		.order_conter {
			// background-color: pink;
			margin-top: 80rpx;
			height: 1134rpx;

			.swiper {
				// background-color: pink;
				height: 100%;

				// border: none;
				.tab-content {
					.list-scroll-content {
						height: 1134rpx;
					}

					.order_conter_items {

						color: #999999;

					}

					.makeAppointment_item {
						background-color: #FFFFFF;
						border-radius: 10rpx;
						width: 700rpx;
						// height: 400rpx;
						margin: 15rpx auto;
						padding: 10rpx 0;
						box-sizing: border-box;

						&_title {
							font-size: 26rpx;
							color: #ff3200;
							// background-color: pink;
							text-align: right;
							margin-right: 20rpx;
						}

						.title1 {
							color: #7d7d7d;
						}

						&_conter {
							border-bottom: 1px solid #F5F5F5;
							// background-color: pink;
							padding: 10rpx 30rpx;

							.makeAppointment_item_demo {
								display: flex;
								align-items: center;
								justify-content: space-between;
								// background-color: pink;

								box-sizing: border-box;

								&_left {
									display: flex;
									align-items: center;

									.image {
										width: 100rpx;
										height: 100rpx;
										// background-color: #4CD964;

										image {
											width: 100rpx;
											height: 100rpx;
											border-radius: 10rpx;
										}
									}

									.conter {
										font-size: 24rpx;
										color: #282828;
										width: 400rpx;
										// background-color: red;
										margin-left: 15rpx;
										// 多行显示超出部分显示省略号
										overflow: hidden;
										text-overflow: ellipsis;
										display: -webkit-box;
										-webkit-box-orient: vertical;
										-webkit-line-clamp: 2;
										word-break: break-all;
									}
								}

								.number {
									width: 200rpx;
									text-align: right;
									font-size: 24rpx;
									color: #282828;

									// background-color: #007AFF;
									.number1 {
										color: #ff3200;
									}
								}
							}

							.price {
								// background-color: red;
								font-size: 26rpx;
								color: #000000;
								text-align: right;
							}
						}

						&_make {
							// background-color: red;
							display: flex;
							justify-content: flex-end;
							padding-right: 10px;

							view {
								// background-color: pink;
								width: 180rpx;
								height: 50rpx;
								line-height: 50rpx;
								border-radius: 50rpx;
								text-align: center;
								font-size: 24rpx;
								color: #FFFFFF;
								margin: 10rpx 20rpx 0;
							}

							.name1 {
								background-color: #ff3200;
								width: 120rpx;
							}

							.name2 {
								background-color: #efefef;
								color: #7d7d7d;
								width: 130rpx;
							}
							.isactive{
								background-color:#ff3200 ;
								color: #FFFFFF;
							}

							.name3 {
								background-color: #efefef;
								color: #7d7d7d;
								// width: 200rpx;
								margin-left: 10rpx;
							}

							.name4 {
								// width: 220rpx;
								// background-color: pink;								
								margin-right: 0rpx;
								margin-left: 10rpx;
							}
						}
					}

				}
			}
		}
	}
</style>
